//
//  HomeViewController.m
//  SimpleNote
//
//  Created by mac on 2017/11/21.
//  Copyright © 2017年 上海LOL信息技术服务有限公司. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeTableViewCell.h"
#import "EditViewController.h"
#import "UIBarButtonItem+SRExtension.h"
#import <MMDrawerController.h>
#import <UIViewController+MMDrawerController.h>
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import <WCAlertView.h>
#import <MJRefresh.h>



@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) UIButton *addButton;
@property (nonatomic,strong) NSMutableArray *dataArray;


@end

static NSString * HomeTableViewCellID = @"HomeTableViewCellID";

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self p_postData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ----  UITableViewDelegate/UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HomeTableViewCellID forIndexPath:indexPath];
    BookRecord *record = self.dataArray[indexPath.row];
    cell.titleLabel.text = record.title;
    cell.contentLabel.text = record.content;
    cell.timeLabel.text = record.time;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    EditViewController *edit = [[EditViewController alloc]init];
    edit.recordModel = self.dataArray[indexPath.row];
    [self.navigationController pushViewController:edit animated:YES];
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"delete" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [WCAlertView showAlertWithTitle:NSLocalizedString(@"The file will not be restored after the file is deleted",nil) message:nil customizationBlock:nil completionBlock:^(NSUInteger buttonIndex, WCAlertView *alertView) {
            if (buttonIndex == 1) {
                // cancel
            }else{
                // delete
                BookRecord *record = self.dataArray[indexPath.row];
                [[DataOperationLayer shareInstance]deleteBookRecord:record];
                [self.dataArray removeObjectAtIndex:indexPath.row];
                [self.tableview deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                [self.tableview reloadData];
            }
        } cancelButtonTitle:NSLocalizedString(@"delete",nil) otherButtonTitles:NSLocalizedString(@"cancel",nil), nil];
    }];
    return @[deleteAction];
}

#pragma mark ---  DZNEmptyDataSetSource/DZNEmptyDataSetDelegate
-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"none"];
}

-(NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView{
    NSString *text = NSLocalizedString(@"You haven't taken notes yet",nil);
    return [[NSAttributedString alloc]initWithString:text attributes:nil];
}


-(void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view{
    EditViewController *edit = [[EditViewController alloc]init];
    [self.navigationController pushViewController:edit animated:YES];
}


#pragma mark -- Action
-(void)addButtonClick:(UIButton *)sender{
    EditViewController *edit = [[EditViewController alloc]init];
    [self.navigationController pushViewController:edit animated:YES];
}

-(void)complectionAction{
    
    if (self.mm_drawerController.visibleLeftDrawerWidth>0) {
        [self.mm_drawerController closeDrawerAnimated:YES completion:nil];
    }else{
        [self.mm_drawerController openDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
    }
}

#pragma mark --- private method
-(void)p_postData{
    [SVProgressHUD show];
    AVQuery *query = [AVQuery queryWithClassName:@"BijiList"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        [SVProgressHUD dismiss];
        [self.tableview.mj_header endRefreshing];
        self.dataArray = [[[DataOperationLayer shareInstance]selectAllBookRecord] mutableCopy];
        [self.tableview reloadData];
    }];
}


#pragma mark --- setup UI
-(void)setupUI{
    
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.title = NSLocalizedString(@"My Notes", nil);
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTitle:NSLocalizedString(@"setting", nil) addTarget:self action:@selector(complectionAction)];
    
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(NavigationBarHeight);
    }];
    
    [self.view addSubview:self.addButton];
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-20);
        make.bottom.equalTo(self.view).offset(-50);
        make.width.height.mas_equalTo(50);
    }];
    self.addButton.layer.cornerRadius = 25;
    
    __weak typeof(self) weakself = self;
    MJRefreshHeader *header = [MJRefreshHeader headerWithRefreshingBlock:^{
        [weakself p_postData];
    }];
    self.tableview.mj_header = header;
}

#pragma mark --- set get

-(UITableView *)tableview{
    if (_tableview == nil) {
        _tableview = [[UITableView alloc]init];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        [_tableview registerClass:[HomeTableViewCell class] forCellReuseIdentifier:HomeTableViewCellID];
        _tableview.tableFooterView = [[UIView alloc]init];
        
        // 必须setting预估高度才能生效
        _tableview.estimatedRowHeight = 100;
        _tableview.rowHeight = UITableViewAutomaticDimension;
        
        // setting空视图
        _tableview.emptyDataSetSource = self;
        _tableview.emptyDataSetDelegate = self;
    }
    return _tableview;
}

-(UIButton *)addButton{
    if (_addButton == nil) {
        _addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addButton addTarget:self action:@selector(addButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_addButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
        [_addButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateHighlighted];
    }
    return _addButton;
}

@end
